//
//  PrivateChatView.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2023/7/2.
//

#import "PrivateChatView.h"
#import <LSTPopView.h>
//其他人的消息
#import "ChatLeftCell.h"
//我的消息
#import "ChatMeCell.h"
#import "AFNetworking.h"
#import "PrivateChatListModel.h"
#import "PrivateImgCell.h"
#import "YBImageBrowser.h"
@interface PrivateChatView ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (nonatomic,weak) LSTPopView *popView;
@property(nonatomic,strong) NSMutableArray <PrivateChatListModel*> *messageArray;
@property (nonatomic, strong) UITableView *tableView;
@property(nonatomic,strong)UIButton *messageBtn;
@property(nonatomic,strong)UITextView *chatTextView;
@property(nonatomic,strong)UIButton *sendbutton;
@property(nonatomic,strong)UIView *chatInputView;
@property(nonatomic,strong)UIView *view;
@property(nonatomic,strong)UILabel *user;
@end

static PrivateChatView *sharedView = nil;
static dispatch_once_t onceToken;
@implementation PrivateChatView

+ (instancetype)sharedView {
    
//    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedView = [[PrivateChatView alloc] init];
    });
    return sharedView;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
//        BOOL isShowingOnScreen = CGRectIntersectsRect(self.frame, UIScreen.mainScreen.bounds);
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8);
        
        self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/3*2.2-110)];
        self.view.backgroundColor = rgba(243, 243, 243, 1.0);
        [self addSubview:self.view];
        self.messageArray = [NSMutableArray array];
        
        self.user = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, SCREEN_WIDTH-30, 20)];
        self.user.font = [UIFont systemFontOfSize:16];
        self.user.textAlignment = 1;
        [self addSubview:self.user];
   
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, 30, SCREEN_WIDTH-30, self.view.frame.size.height-60) style:UITableViewStylePlain];
        _tableView.backgroundColor = rgba(243, 243, 243, 1.0);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = false;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 100;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[ChatLeftCell class] forCellReuseIdentifier:@"ChatLeftCell"];
        [_tableView registerClass:[PrivateImgCell class] forCellReuseIdentifier:@"PrivateImgCell"];
        
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
        
        if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            
        }
        _tableView.transform = CGAffineTransformMakeScale(1, -1);
        
        self.messageBtn = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"comment"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(messageAction) layer:20];
        [self.view addSubview:self.messageBtn];
        [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(40);
            make.right.mas_equalTo(self).offset(-15);
            make.bottom.mas_equalTo(self).offset(-30);
        }];
        
        
        self.chatInputView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-50, SCREEN_WIDTH, 50)];
        self.chatInputView.layer.cornerRadius = 10;
        self.chatInputView.layer.masksToBounds = YES;
        self.chatInputView.hidden = YES;
        self.chatInputView.backgroundColor = rgba(245, 246, 250, 1);
        [self.view addSubview:self.chatInputView];
        
        self.chatTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 10,SCREEN_WIDTH-80 , 30)];
        self.chatTextView.font = [UIFont systemFontOfSize:14];
        self.chatTextView.delegate = self;
        self.chatTextView.editable = YES;
        self.chatTextView.layer.cornerRadius = 5;
        self.chatTextView.inputAccessoryView = [UIView new];
        self.chatTextView.returnKeyType = UIReturnKeyDone;
        [self.chatInputView addSubview:self.chatTextView];
        
        self.sendbutton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectMake(SCREEN_WIDTH-70, 10, 55, 30) image:nil title:@"发送" font:[UIFont systemFontOfSize:13] backColot:rgba(25, 148, 255, 1) textColor:[UIColor whiteColor] target:self action:@selector(sendMessage) layer:3];
        [self.chatInputView addSubview:self.sendbutton];
    }
    return self;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 7;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.messageArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(self.messageArray[indexPath.section].send == self.model.userId){
    if (![Tool strIsNULL:self.messageArray[indexPath.section].imageurl]) {
        PrivateImgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PrivateImgCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.message = self.messageArray[indexPath.section];
        cell.transform = CGAffineTransformMakeScale(1, -1);
        return  cell;
    }else
    {
        ChatLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatLeftCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.message = self.messageArray[indexPath.section];
    cell.backgroundColor =  rgba(243, 243, 243, 1.0);
    if(self.messageArray[indexPath.section].send == self.model.userId){
        cell.content.backgroundColor = [UIColor whiteColor];
    }else{
        cell.content.backgroundColor = rgba(169, 234, 122, 1.0);
    }
        
        cell.transform = CGAffineTransformMakeScale(1, -1);

        return  cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.messageArray[indexPath.section].imageurl) {
        PrivateChatListModel *model = self.messageArray[indexPath.section];
        NSMutableArray *datas = [NSMutableArray array];
        YBIBImageData *data = [YBIBImageData new];
        data.imageURL = [NSURL URLWithString:model.imageurl];
        [datas addObject:data];
       YBImageBrowser *browser = [YBImageBrowser new];
       browser.dataSourceArray = datas;
       browser.currentPage = 0;
       [browser show];
    }
}
#pragma mark - 发消息
- (void)messageAction
{
    NSLog(@"messageAction");
    self.chatInputView.hidden = NO;
    [self.chatTextView becomeFirstResponder];
    [_popView setValue:@1 forKeyPath:@"_backgroundView.alpha"];
    [_popView setValue:[UIColor  whiteColor] forKeyPath:@"_backgroundView.backgroundColor"];
}


- (void)setModel:(PrivateModel *)model
{
    _model = model;
    
    self.user.text = model.userName;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/chat/%@/?user_id=%@&pages=200",HTTPSURL,self.model.liveId,self.model.userId];
    NSDictionary *auth = @{@"authorization":[NSString stringWithFormat:@"jwt %@",self.model.token]};
    __weak typeof(self) weakSelf = self;
    [manager GET:urlString parameters:nil headers:auth progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] intValue] == 200){
            NSArray<PrivateChatListModel *>*array = [PrivateChatListModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
            weakSelf.messageArray = [array mutableCopy];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}

- (void)sendMessage
{
    if([self.chatTextView.text isEqualToString:@""]){
        [[ZXMessageCase shareInstace] showMessage:@"不能发送空消息"];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSDictionary *params = @{@"user_id": self.model.userId, @"content": self.chatTextView.text};
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/chat/%@/",HTTPSURL,self.model.liveId];
    NSDictionary *auth = @{@"authorization":[NSString stringWithFormat:@"jwt %@",self.model.token]};
    __weak typeof(self) weakSelf = self;
    [manager POST:urlString parameters:params headers:auth progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if([responseObject[@"code"] intValue] == 200){
            
           NSDictionary *dicn = [[YouinRTCManager shardManager] readUserInfo];
            
            PrivateChatListModel *model = [[PrivateChatListModel alloc] init];
            model.content = self.chatTextView.text;
            model.send_nickname = dicn[@"name"];
            model.send_image = dicn[@"avatar"];
            [self.messageArray insertObject:model atIndex:0];
            [self.tableView reloadData];
            [weakSelf.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
          
        }else{
            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
        }
        weakSelf.chatTextView.text = @"";
        [weakSelf.chatTextView resignFirstResponder];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error == $error");
    }];
    
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    self.chatInputView.hidden = YES;
    [self.chatTextView resignFirstResponder];
    self.chatTextView.text = @"";
    [_popView setValue:RGBA(0, 0, 0, 0.25) forKeyPath:@"_backgroundView.backgroundColor"];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder]; // 隐藏键盘
        
        return NO;
    }
    return YES;
}

-(void)show
{
    LSTPopView *popView = [LSTPopView initWithCustomView:self
                                                popStyle:LSTPopStyleSmoothFromBottom
                                            dismissStyle:LSTDismissStyleSmoothToBottom];
    
    popView.hemStyle = LSTHemStyleBottom;
    popView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    LSTPopViewWK(popView)
    popView.popDuration = 0.5;
    popView.dismissDuration = 0.5;
    popView.isClickFeedback = YES;
    popView.rectCorners = UIRectCornerTopLeft | UIRectCornerTopRight;
    popView.cornerRadius = 15;
    popView.sweepStyle = LSTSweepStyleY_Positive;
    popView.dragStyle = LSTDragStyleNO;
    popView.sweepDismissStyle = LSTSweepDismissStyleSmooth;
    popView.bgClickBlock = ^{
        NSLog(@"点击了背景");
       
        [wk_popView dismiss];
    };
    self.popView = popView;
    
    [popView pop];
}

-(void)dealloc
{
   
    NSLog(@"dealloc");
}
+ (void)clearSharedView {
    onceToken = 0;
    sharedView = nil;
}
@end
